package com.codi.api.xxljob;

import com.codi.base.util.ListUtil;
import com.codi.bus.constant.CacheKeyConst;
import com.codi.bus.constant.GlobalConstant;
import com.codi.bus.core.domain.FundInfo;
import com.codi.bus.core.service.FundDetailService;
import com.codi.bus.core.service.FundInfoService;
import com.codi.bus.core.util.JobUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * @author lvgo
 * @version 1.0
 * @Description: 刷新基金类型
 * 0 0 2 ? * 7
 * @date 18-6-29 下午5:41
 */
@Slf4j
@Component
@JobHandler("fundTypeHandler")
public class FundTypeHandler extends IJobHandler {
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private FundInfoService fundInfoService;
    @Resource
    private FundDetailService fundDetailService;

    @Override
    public ReturnT<String> execute(String param) throws Exception {
        Set<String> keys = redisTemplate.keys(CacheKeyConst.MF_FUND_TYPE + ":*");
        if (keys != null && !keys.isEmpty()) {
            log.debug("fund type keys length={}", keys.size());
            redisTemplate.delete(keys);
        }
        int pageIndex = 1;
        while (true) {
            log.debug("loading fund pageIndex={}", pageIndex);
            List<FundInfo> funds = fundInfoService.queryPage(GlobalConstant.PAGE_SIZE, pageIndex);
            if (ListUtil.isNotEmpty(funds)) {
                for (FundInfo fund : funds) {
                    fundDetailService.getFundDetail(fund.getFundCode());
                }
                if (funds.size() < GlobalConstant.PAGE_SIZE) {
                    break;
                }
            } else {
                break;
            }
            pageIndex++;
        }
        JobUtil.updateJobExecuteTime(CacheKeyConst.MF_FUND_TYPE);
        XxlJobLogger.log("FundTypeHandler, success");
        return SUCCESS;
    }
}
